//
//  SWBook.swift
//  YiyaPuzzleDemo
//
//  Created by linhan on 16/9/29.
//  Copyright © 2016年 test. All rights reserved.
//

import Foundation
import UIKit


class SWPhotoWrapper: NSObject
{
    var photo:SWPhoto
    var image:UIImage?
    
    init(photo:SWPhoto)
    {
        self.photo = photo
    }
    
}

extension SWBook
{
    //从模板中更新
    func updateFromTemplate(_ template:SWBookTemplate)
    {
        trace("SWBook,updateFromTemplate")
        version = template.version
        if let localPages = pages?.flatMap({$0 as? SWPage}),
           let templates = template.pages?.flatMap({$0 as? SWPageTemplate})
        {
            for page in localPages
            {
                if let index = templates.index(where: {($0.pageID ?? "") == (page.pageID ?? "")}),
                   let template = templates.valueAt(index), template.version > page.version
                {
                    page.updateFromTemplate(template)
                    //完整的页面再重新生成一遍
                    print("completeness:", page.completeness)
                    if page.completeness
                    {
                        let task = SWGenerationTask(page:page)
                        SWPageManager.sharedManager().addTask(task)
                    }
                }
            }//end for
        }//end if let
    }
    
    
}

extension SWPage
{
    convenience init(template:SWPageTemplate)
    {
        self.init()
        
        version = template.version
        title = template.title
        eventID = template.eventID
        pageID = template.pageID ?? StringUtil.getUniqid(5)
        previewBgURL = template.previewBgURL
        largeBgURL = template.largeBgURL
        photos = template.photos?.flatMap({$0 as? SWPhotoTemplate}).map({SWPhoto(template:$0)})
        texts = template.texts?.flatMap({$0 as? SWTextTemplate}).map({SWText(template:$0)})
    }
    
    var editable:Bool?{
        return true
    }
    
    //有效的图片
    var existingImageIDs:[String]
    {
        var existingIDs:[String] = []
        let manager = SWBookAssetManager.sharedManager()
        let imageIDs = self.photos.flatMap({($0 as? SWPhoto)?.imageID}).filter({$0 != ""})
        for id in imageIDs
        {
            if manager.photoExists(id, level: .processed) || manager.photoExists(id, level: .origin)
            {
                existingIDs.append(id)
            }
        }
        return existingIDs
    }
    
    //页面是否完善（照片是否填满）
    var completeness:Bool
    {
        //可编辑的页面必选全部填满
        //let editable:Bool = editable ?? true
        if (editable ?? true)
        {
            let aPhotos:[SWPhoto] = photos?.flatMap({$0 as? SWPhoto}) ?? []
            for photo in aPhotos
            {
                guard let imageID = photo.imageID,
                      let bookID = bookID, imageID != "" && bookID != "" && SWBookAssetManager.sharedManager().photoExists(imageID, level: .processed) else {
                    return false
                }
            }
        }
        return true
    }
    
    //从模板中更新
    func updateFromTemplate(_ template:SWPageTemplate)
    {
        trace("页面更新:", pageID)
        version = template.version
        previewBgURL = template.previewBgURL
        largeBgURL = template.largeBgURL
        
        if let templatePhotos = template.photos?.flatMap({$0 as? SWPhotoTemplate})
        {
            if photos.count < templatePhotos.count   //本地数少于模板数，则进行创建
            {
                for _ in 0..<(templatePhotos.count - photos.count)
                {
                    photos.append(SWPhoto())
                }
            }
            else if photos.count > templatePhotos.count  //多余的进行删除
            {
                photos.removeLast(photos.count - templatePhotos.count)
            }
            
            for i in 0..<photos.count
            {
                if let template = templatePhotos.valueAt(i)
                {
                    (photos.valueAt(i) as? SWPhoto)?.updateFromTemplate(template)
                }
            }
        }
        
        if let templateTexts = template.texts?.flatMap({$0 as? SWTextTemplate})
        {
            if texts.count < templateTexts.count   //本地数少于模板数，则进行创建
            {
                for _ in 0..<(templateTexts.count - texts.count)
                {
                    texts.append(SWText())
                }
            }
            else if texts.count > templateTexts.count  //多余的进行删除
            {
                texts.removeLast(texts.count - templateTexts.count)
            }
            
            for i in 0..<texts.count
            {
                if let template = templateTexts.valueAt(i)
                {
                    (texts.valueAt(i) as? SWText)?.updateFromTemplate(template)
                }
            }
        }
        
        
    }
    
    //是否包含某张图片
    func containsPhoto(imageID:String) -> Bool
    {
        if let photos = photos?.flatMap({$0 as? SWPhoto})
        {
            return photos.contains(where: {($0.imageID ?? "") == imageID})
        }
        return false
    }
    
    func loadPhotoFromEvent()
    {
        if let photos = photos,
            let eventID = eventID,eventID != "" && photoImportedTime == 0 && category == .event
        {
            let cellCount:Int = photos.count
            let assets:[SWAssetRecord] = SWAssetsManager.sharedManager().fetchEventPhotoForBook(eventID: eventID)
            let length:Int = min(assets.count, cellCount)
            var localIdentifiers:[String] = assets.flatMap({$0.localID})
            localIdentifiers = localIdentifiers[0..<length].map({$0})
            
            if localIdentifiers.count > 0
            {
                photoImportedTime = Int(Date().timeIntervalSince1970)
                //导入照片
                var options = SWALPhotoRequestOptions()
                options.requestImageData = true
                SWAssetsLibraryHelper.shared().fetchOriginImage(localIdentifiers: localIdentifiers, options: options, completeCallback: {[weak self] results in
                    
                    for (index, result) in results.enumerated()
                    {
                        if let image = result.image,
                            let data:Data = result.data ?? UIImageJPEGRepresentation(image, 0.8)
                        {
                            let imageID:String = SWBookAssetManager.sharedManager().addPhoto(image, data: data)
                            (photos.valueAt(index) as? SWPhoto)?.imageID = imageID
                        }
                    }
                    if let strongSelf = self{
                        strongSelf.importedFirstTime = true
                        SWBookManager.sharedManager().save(page:strongSelf)
                        //导入事件取第一张图片的事件
                        if let date = results.first?.creationDate{
                            strongSelf.photoImportedTime = Int(date.timeIntervalSince1970)
                        }
                        
                    }
                    
                    let pageID:String = self?.pageID ?? ""
                    SWNotificationCenter.post(name: NotificationName.BookPageUpdated, object: nil, userInfo: [SWKey.pageID:pageID])
                    
                })// end fetchOriginImage
                
                
            }//end localIdentifiers
            
            
            
        }
        
        
    }//end func
    
    
    
}

extension SWOrderRecord
{
    var unuploadedPages:[SWPage]
    {
        return pages?.flatMap({$0 as? SWPage}).filter({$0.largeResultURL == nil || $0.largeResultURL == ""}) ?? []
    }
    
    var uploadedPages:[SWPage]
    {
        return pages?.flatMap({$0 as? SWPage}).filter({($0.largeResultURL?.length ?? 0) > 0}) ?? []
    }
}

extension SWPhoto
{
    convenience init(template:SWPhotoTemplate)
    {
        self.init()
        
        updateFromTemplate(template)
    }
    
    //从模板中更新
    func updateFromTemplate(_ template:SWPhotoTemplate)
    {
        xPercent = template.xPercent
        yPercent = template.yPercent
        widthPercent = template.widthPercent
        heightPercent = template.heightPercent
    }
    
    //交换两个SWPhoto的内容
    class func swapContent(_ lhs:SWPhoto, rhs:SWPhoto)
    {
        let tempImageID:String? = lhs.imageID
        let tempLocalID:String? = lhs.localID
        let tempRemoteURL:String? = lhs.remoteURL
        let tempSectionID:String? = lhs.sectionID
        let tempText:String? = lhs.text
        let tempCreateDate:NSNumber? = lhs.createDate
        
        lhs.imageID = rhs.imageID
        lhs.localID = rhs.localID
        lhs.remoteURL = rhs.remoteURL
        lhs.sectionID = rhs.sectionID
        lhs.text = rhs.text
        lhs.createDate = rhs.createDate
        
        rhs.imageID = tempImageID
        rhs.localID = tempLocalID
        rhs.remoteURL = tempRemoteURL
        rhs.sectionID = tempSectionID
        rhs.text = tempText
        rhs.createDate = tempCreateDate
    }
}

extension SWText
{
    convenience init(template:SWTextTemplate)
    {
        self.init()
        text = template.defaultText
        textColor = template.textColor
        fontSize = template.fontSize
        xPercent = template.xPercent
        yPercent = template.yPercent
        widthPercent = template.widthPercent
        heightPercent = template.heightPercent
    }
    
    //从模板中更新
    func updateFromTemplate(_ template:SWTextTemplate)
    {
        textColor = template.textColor
        fontSize = template.fontSize
        xPercent = template.xPercent
        yPercent = template.yPercent
        widthPercent = template.widthPercent
        heightPercent = template.heightPercent
    }
}

extension SWBookTemplate
{
    convenience init(response:SWBookTemplateRsp)
    {
        self.init()
        templateID = response.id
        version = response.version ?? 0
        title = response.title
        category = SWBookCategory(rawValue: response.category ?? 0) ?? category
        pages = response.pages?.map({SWPageTemplate(response: $0)})
    }
}

extension SWPageTemplate
{
    convenience init(response:SWPageTemplateRsp)
    {
        self.init()
        version = response.version ?? 0
        eventID = response.eventID
        title = response.title
        pageID = response.pageID
        previewBgURL = response.previewBgURL
        largeBgURL = response.largeBgURL
        photos = response.photos?.map({SWPhotoTemplate(response: $0)})
        texts = response.texts?.map({SWTextTemplate(response: $0)})
        
    }
}

extension SWPhotoTemplate
{
    convenience init(response:SWPhotoTemplateRsp)
    {
        self.init()
        xPercent = response.xPercent ?? 0
        yPercent = response.yPercent ?? 0
        widthPercent = response.widthPercent ?? 0
        heightPercent = response.heightPercent ?? 0
    }
}

extension SWTextTemplate
{
    convenience init(response:SWTextTemplateRsp)
    {
        self.init()
        defaultText = response.defaultText
        textColor = response.textColor
        fontSize = response.fontSize ?? 0
        xPercent = response.xPercent ?? 0
        yPercent = response.yPercent ?? 0
        widthPercent = response.widthPercent ?? 0
        heightPercent = response.heightPercent ?? 0
    }
}


